package com.zzyl.nursing.service.impl;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.huaweicloud.sdk.iotda.v5.IoTDAClient;
import com.huaweicloud.sdk.iotda.v5.model.*;
import com.zzyl.common.core.domain.AjaxResult;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.DateUtils;
import com.zzyl.nursing.dto.DeviceDto;
import com.zzyl.nursing.util.DateTimeZoneConverter;
import com.zzyl.nursing.vo.DeviceDataVo;
import com.zzyl.nursing.vo.DeviceDetailVo;
import com.zzyl.nursing.vo.ProductVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.mapper.DeviceMapper;
import com.zzyl.nursing.domain.Device;
import com.zzyl.nursing.service.IDeviceService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import java.util.Arrays;
/**
 * 设备类型Service业务层处理
 * 
 * @author lpz
 * @date 2025-10-17
 */
@Service
public class DeviceServiceImpl extends ServiceImpl<DeviceMapper,Device> implements IDeviceService
{
    @Autowired
    private DeviceMapper deviceMapper;

    /**
     * 查询设备类型
     * 
     * @param id 设备类型主键
     * @return 设备类型
     */
    @Override
    public Device selectDeviceById(Long id)
    {
        return getById(id);
    }

    /**
     * 查询设备类型列表
     * 
     * @param device 设备类型
     * @return 设备类型
     */
    @Override
    public List<Device> selectDeviceList(Device device)
    {
        return deviceMapper.selectDeviceList(device);
    }

    /**
     * 新增设备类型
     * 
     * @param device 设备类型
     * @return 结果
     */
    @Override
    public int insertDevice(Device device)
    {
        return save(device)?1:0;
    }

    /**
     * 修改设备类型
     * 
     * @param device 设备类型
     * @return 结果
     */
    @Override
    public int updateDevice(Device device)
    {
        return updateById(device)?1:0;
    }

    /**
     * 批量删除设备类型
     * 
     * @param ids 需要删除的设备类型主键
     * @return 结果
     */
    @Override
    public int deleteDeviceByIds(Long[] ids)
    {
        return removeByIds(Arrays.asList(ids))?1:0;
    }

    /**
     * 删除设备类型信息
     * 
     * @param id 设备类型主键
     * @return 结果
     */
    @Override
    public int deleteDeviceById(Long id)
    {
        return removeById(id)?1:0;
    }

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    @Autowired
    private IoTDAClient ioTDAClient;

    /**
     * 同步产品列表
     */
    public static final String IOT_ALL_PRODUCT_LIST= "iot:all_product_list";
    @Override
    public void syncProductList() {
        ListProductsRequest listProductsRequest = new ListProductsRequest();
        listProductsRequest.setLimit(50);
        ListProductsResponse response = ioTDAClient.listProducts(listProductsRequest);
        if(response.getHttpStatusCode() != 200){
            throw new BaseException("物联网接口 - 查询产品，同步失败");
        }
        List<ProductSummary> products = response.getProducts();
        redisTemplate.boundValueOps(IOT_ALL_PRODUCT_LIST).set(JSONUtil.toJsonStr(products));

    }

    /**
     * 查询所有产品列表
     *
     * @return
     */
    @Override
    public List<ProductVo> allProduct() {

        String s = redisTemplate.boundValueOps(IOT_ALL_PRODUCT_LIST).get();
        if (s!=null) {
            List<ProductVo> productVos = JSONUtil.toList(s, ProductVo.class);
            return productVos;
        }

        return List.of();
    }


    /**
     * 注册设备
     * @param dto
     */
    @Override
    public void registerDevice(DeviceDto dto) {
        LambdaQueryWrapper<Device> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Device::getDeviceName,dto.getDeviceName());
        if (this.count(queryWrapper)>0) {
            throw new BaseException("设备名称重复");
        }

        queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Device::getNodeId,dto.getNodeId());
        if (this.count(queryWrapper)>0) {
            throw new BaseException("设备标识重复");
        }
        queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Device::getLocationType,dto.getLocationType());
        queryWrapper.eq(Device::getBindingLocation,dto.getBindingLocation());
        queryWrapper.eq(Device::getProductKey,dto.getProductKey());
        if (this.count(queryWrapper)>0) {
            throw new BaseException("同一个位置绑定了相同的产品");
        }

        AddDeviceRequest request = new AddDeviceRequest();
        AddDevice body = new AddDevice();
        body.setNodeId(dto.getNodeId());
        body.setDeviceName(dto.getDeviceName());
        body.setProductId(dto.getProductKey());
        AuthInfo authInfo = new AuthInfo();
        String secret = RandomUtil.randomString(32);
        authInfo.setSecret(secret);
        body.setAuthInfo(authInfo);
        body.setDescription(dto.getDeviceDescription());
        request.setBody(body);
        AddDeviceResponse response = ioTDAClient.addDevice(request);
        if (response.getHttpStatusCode()!=201) {
            throw new BaseException("IOT设备添加失败");
        }
        String deviceId = response.getDeviceId();

        Device device = BeanUtil.toBean(dto, Device.class);
        device.setIotId(deviceId);
        device.setSecret(secret);

        this.save(device);
    }



    @Override
    public DeviceDetailVo deviceDetail(String iotId) {
        ShowDeviceRequest request = new ShowDeviceRequest();
        request.setDeviceId(iotId);
        ShowDeviceResponse response = ioTDAClient.showDevice(request);
        if (response.getHttpStatusCode()!=200) {
            throw new BaseException("IOT设备查询失败");
        }
        Device device = this.getOne(new LambdaQueryWrapper<Device>().eq(Device::getIotId,iotId));
        if (device==null) {
            throw new BaseException("设备不存在");
        }

        DeviceDetailVo deviceDetailVo = BeanUtil.toBean(device, DeviceDetailVo.class);

        deviceDetailVo.setDeviceStatus(response.getStatus());

        String activeTimeStr = response.getActiveTime();
        if (activeTimeStr != null) {
            LocalDateTime parse = LocalDateTimeUtil.parse(activeTimeStr, DatePattern.UTC_MS_PATTERN);
            LocalDateTime activeTime = DateTimeZoneConverter.utcToShanghai(parse);
            deviceDetailVo.setActiveTime(activeTime);
        }

        return deviceDetailVo;
    }



    @Override
    public List<DeviceDataVo>queryServiceProperties(String iotId) {

        List<DeviceDataVo> list = new ArrayList<>();


        ShowDeviceShadowRequest request = new ShowDeviceShadowRequest();
        request.setDeviceId(iotId);
        ShowDeviceShadowResponse response = ioTDAClient.showDeviceShadow(request);
        if (response.getHttpStatusCode()!=200) {
            throw new BaseException("IOT设备查询失败");
        }

        List<DeviceShadowData> shadowList = response.getShadow();
        if(CollUtil.isNotEmpty(shadowList)){



            DeviceShadowData deviceShadowData = shadowList.get(0);
            DeviceShadowProperties reported = deviceShadowData.getReported();
            String eventTimeStr = reported.getEventTime();
            LocalDateTime eventTimeUTC = LocalDateTimeUtil.parse(eventTimeStr, "yyyyMMdd'T'HHmmss'Z'");
            LocalDateTime eventTime = DateTimeZoneConverter.utcToShanghai(eventTimeUTC);

            Object properties = reported.getProperties();
            JSONObject jsonObject = JSONUtil.parseObj(properties);
            jsonObject.forEach((key,value)->{
                DeviceDataVo deviceDataVo = new DeviceDataVo();
                deviceDataVo.setFunctionId(key);
                deviceDataVo.setEventTime(eventTime);
                deviceDataVo.setValue(value);
                list.add(deviceDataVo);
            });
        }
        return list;
    }
    //修改 设备
    @Override
    public void upDataDevice(DeviceDto dto) {
        Device byId = this.getById(dto.getId());
        if (byId==null){
            throw new BaseException("没有此设备");
        }
        UpdateDeviceRequest request = new UpdateDeviceRequest();
        request.setDeviceId(dto.getIotId());
        UpdateDevice body = new UpdateDevice();
        AuthInfoWithoutSecret authInfobody = new AuthInfoWithoutSecret();
        authInfobody.withSecureAccess(true);
        body.setAuthInfo(authInfobody);
        body.setDeviceName(dto.getDeviceName());
        body.setDescription(dto.getDeviceDescription());
        request.setBody(body);
        Device device = BeanUtil.toBean(dto, Device.class);
        this.updateDevice(device);
    }
    //删除设备
    @Override
    public void deleteDevice(String iotId) {
        LambdaQueryWrapper<Device> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Device::getIotId,iotId);
        Device one = getOne(queryWrapper);
        if(one==null){
            throw new BaseException("没有此设备");
        }
        DeleteDeviceRequest request = new DeleteDeviceRequest();
        request.setDeviceId(iotId);
        try {
            ioTDAClient.deleteDevice(request);
        } catch (Exception e) {
            throw  new BaseException("同步失败");
        }

        this.removeById(one.getId());
    }

    @Override
    public AjaxResult queryProduct(String productKey) {
        ShowProductRequest request =new  ShowProductRequest();
        request.setProductId(productKey);
        ShowProductResponse response = ioTDAClient.showProduct(request);
        if (response.getHttpStatusCode()!=200){
            throw new BaseException("IOT设备查询失败");
        }
        List<ServiceCapability> serviceCapabilities = response.getServiceCapabilities();
        return AjaxResult.success(serviceCapabilities);
    }
}
